package com.dream.xcarrecorder.test;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import com.dream.libxrec.rec.audio.MP3Recorder;
import com.dream.libxrec.sound.ISoundRec;
import com.dream.libxrec.sound.XAudioRecord;
import java.io.File;

public class MP3Tester {

    private ISoundRec mAudioRec;
    private MP3Recorder mMp3Rec;
    private String mAudioPath = "";

    private static final int SOUND_SAMPLE = 16000;//音频采样率
    private static final int SOUND_CHANNEL = 2;//音频通道数
    private static final int SOUND_BITRATE = 16000;//音频码率

    public void startRec(Context ct){

        mAudioPath =
                ct.getExternalFilesDir(Environment.DIRECTORY_PICTURES)+ File.separator+"recorder"+ SystemClock.uptimeMillis()+".mp3";

        //MP3编码
        mMp3Rec = new MP3Recorder(ct,mAudioPath,
                SOUND_SAMPLE,SOUND_CHANNEL,SOUND_BITRATE,9,true);

        //采集麦克风数据
        mAudioRec = new XAudioRecord().init(ct,
                SOUND_SAMPLE,
                SOUND_CHANNEL,16,null);
        mAudioRec.setISoundRecListener(new ISoundRec.ISoundRecListener() {
            @Override
            public void onSoundRec(byte[] pcm, int size) {
                if(size > 0){
                    mMp3Rec.write(pcm, size);
                }
            }
        });
        mAudioRec.start();
    }

    public void stopRec(){
        mAudioRec.setISoundRecListener(null);
        mAudioRec.stop();

        mMp3Rec.release();
        Log.i("Test","停止录音");
    }

    public void play(){
        MediaPlayer player = new MediaPlayer();
        try {
            player.setDataSource(mAudioPath);
            player.prepare();
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
